package com.example.downloaddemo;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.example.service.DownloadService;
import com.example.service.DownloadService.DownloadBinder;

public class MainActivity extends Activity {
	private static final String TAG = "ZL";
	private Button start, stop;
	private ProgressBar pb;
	private DownloadService.DownloadBinder mBinder;
	private DownloadService downloadService;
	private ServiceConnection conn = new ServiceConnection() {

		@Override
		public void onServiceDisconnected(ComponentName name) {
			// 当Service和Activity取消绑定的时候调用
			Log.i(TAG, "MainActivity onServiceDisconnected");
		}

		@Override
		public void onServiceConnected(ComponentName name, IBinder service) {
			//  当Service和Activity绑定的时候调用
			Log.i(TAG, "MainActivity onServiceConnected");
			mBinder= (DownloadBinder) service;
			downloadService  = mBinder.getService();
			downloadService.startDownload();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();

	}

	/**
	 * 初始化控件
	 */
	private void initView() {
		pb = (ProgressBar) findViewById(R.id.pb);
		start = (Button) findViewById(R.id.start);
		stop = (Button) findViewById(R.id.stop);
	}

	/**
	 * onClick事件
	 */
	public void btnClick(View view) {
		switch (view.getId()) {
		case R.id.bind:// 绑定服务
			Intent intent = new Intent(MainActivity.this,DownloadService.class);
			bindService(intent, conn, BIND_AUTO_CREATE);
			Toast.makeText(getApplicationContext(), "绑定服务", 1).show();
			break;
		case R.id.unbind:// 取消绑定
			unbindService(conn);
			Toast.makeText(getApplicationContext(), "取消绑定", 1).show();
			break;
		case R.id.start:// 开始下载
//			downloadService.startDownload();
			Toast.makeText(getApplicationContext(), "开始下载", 1).show();
			break;
		case R.id.stop:// 停止下载
			downloadService.stopDownload();
			Toast.makeText(getApplicationContext(), "停止下载", 1).show();
			break;

		default:
			break;
		}
	}

}
